package com.mmg.spzx.manager.task;

import cn.hutool.core.date.DateUtil;
import com.mmg.spzx.manager.mapper.OrderInfoMapper;
import com.mmg.spzx.manager.mapper.OrderStatisticsMapper;
import com.mmg.spzx.model.entity.order.OrderStatistics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 订单统计定时任务
 */
@Slf4j
@Component
public class OrderStatisticsTask {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    /**
     * 每天凌晨2点执行,统计前一天的订单总金额,并插入到订单统计表中
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void orderTotalAmountStatistics() {
        // 获取前一天的日期
        String createTime = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        // 查询前一天的订单总金额
        OrderStatistics orderStatistics = orderInfoMapper.findOrderStatistics(createTime);
        // 插入到订单统计表中
        if (orderStatistics != null) {
            orderStatisticsMapper.save(orderStatistics);
        }
    }
}
